package com.fast.fast.common.core.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 生成Kaptcha验证码工具类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@ConditionalOnProperty(prefix = "kaptcha", name = "open", havingValue = "true")
@RequiredArgsConstructor
public class KaptchaUtils {

    private final DefaultKaptcha defaultKaptcha;

    /**
     * 使用kaptcha生成验证码字符串,并把验证码图片输出到浏览器
     *
     * @param request
     * @param response
     * @return 验证码字符串
     * @throws Exception
     */
    public String generateKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 生成验证码字符串
        String verifyCode = defaultKaptcha.createText();
        // 根据该验证码生成一张图片
        BufferedImage bufferedImage = defaultKaptcha.createImage(verifyCode);

        // 将验证码字符串保存到session中
        request.getSession().setAttribute("verifyCode", verifyCode);

        // 创建图片输出流
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        // 把图片写入到输出流
        ImageIO.write(bufferedImage, "jpg", outputStream);

        // 设置response
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 将二进制数据输入到浏览器
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(outputStream.toByteArray());
        servletOutputStream.flush();
        servletOutputStream.close();

        return verifyCode;
    }
}
